package com.pipi.fanglan.cookie;

import com.pipi.fanglan.model.MyCookieStore;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * Created by pipi on 2017/7/16.
 */
@Component
public class InMemoryCookieRepository implements CookieRepository {

    private final ConcurrentMap<String,MyCookieStore> cookieStores = new ConcurrentHashMap<>();

    @Override
    public List<MyCookieStore> findAll() {
        return new ArrayList<MyCookieStore>(this.cookieStores.values());
    }

    @Override
    public MyCookieStore save(MyCookieStore myCookieStore) {
        cookieStores.put(myCookieStore.getUserName(),myCookieStore);
        return myCookieStore;
    }

    @Override
    public MyCookieStore findMyCookieStore(String userName) {
        return cookieStores.get(userName);
    }

    @Override
    public MyCookieStore findActive() {
        for(MyCookieStore cookieStore : cookieStores.values()){
            if(cookieStore.isActive()){
                return cookieStore;
            }
        }
        return null;
    }

    @Override
    public void deleteCookieStore(String userName) {
        cookieStores.remove(userName);
    }
}
